var dbConfig = require('../utils/dbconfig.js');
const jwt = require('jsonwebtoken');
const dbconfig = require('../utils/dbconfig.js');


// 登录
async function login(req, res, next) {
    console.log(req.body)
    let username = req.body.username
    let password = req.body.password
    //是否合法的参数
    if (username == null || username.trim() == '' || password == null || password.trim() == '') {
        res.json({ code: 500, message: '用户名密码不能为空' })
        return
    }
    const sql = " SELECT username,role FROM admin_user WHERE username = '" + username +
        "' AND password = '" + password + "'";
    let sqlArr = []
    let callback = (err, data) => {
        if (err) {
            res.json({
                msg: err
            })
            res.status = 401
        } else {
            // 注意默认情况 Token 必须以 Bearer+空格 开头
            const token = 'Bearer ' + jwt.sign(
                req.body,
                'jiao1030',
                {
                    expiresIn: 3600 * 24 * 3
                }
            )
            if (data.length == 1) {
                res.json({
                    data: data[0],
                    status: 200,
                    token: token
                })
            } else {
                res.json({
                    msg: err
                })
                res.status = 400
            }
        }
    }
    dbConfig.sqlConnect(sql, sqlArr, callback)
}
// 获取用户列表
async function getUserlist(req, res, next) {
    let sql = 'SELECT id,username,createTime,phonenum,status,role.roleName from admin_user,role where admin_user.role = role.roleId'
    let sqlArr = []
    let callback = (err, data) => {
        if (err) {
            res.json({
                msg: '暂无数据'
            })
            res.status = 401
        } else {
            res.json(
                {
                    data: data,
                    status: 200,
                },
            )
        }
    }
    dbConfig.sqlConnect(sql, sqlArr, callback)
}
// 添加用户
async function addUser(req, res, next) {
    let username = req.body.username
    let password = req.body.password
    let confirm = req.body.confirm
    let phonenum = req.body.phonenum
    let role = req.body.role
    let status = req.body.status
    let createTime = new Date().getTime() / 1000
    if (username == '' || password == '' || confirm == '' || phonenum == '') {
        res.status = 401
        res.send({
            msg: '请将信息填写完整',
            status: 401,
            body: req.body
        })
        return
    }
    let sql = `insert into admin_user (username, password, createTime, role, phonenum,status) values ('${username}', ${password}, ${createTime}, ${role},${phonenum},${status})`
    let searchsql = `select username from admin_user where username = '${username}'`
    let call = (err, data) => {
        if (err) {
            res.send({
                msg: '添加失败',
                status: 401
            })
            res.status = 401
        } else if (data.affectedRows) {
            res.json({
                msg: '添加成功',
                status: 200
            })
            res.status = 200
        }
        return
    }
    let callback = (err, data) => {
        if (err) {
            res.send({
                msg: '数据库错误',
                status: 401
            })
            res.status = 401
            return
        } else if (data) {
            if (data.length !== 0) {
                res.send({
                    msg: '当前用户已存在',
                    status: 401
                })
                res.status = 401
            } else {
                dbConfig.sqlConnect(sql, [], call)
            }
            return
        }
    }
    dbConfig.sqlConnect(searchsql, [], callback)
}
// 删除用户
async function delUser(req, res, next) {
    let id = req.query.userid
    let sql = `delete from admin_user where id = ${id}`
    let callback = (err, data) => {
        if (err) {
            res.send(
                {
                    msg: '数据库错误',
                    status: 401
                }
            )
            res.status = 401
        } else if (data.affectedRows) {
            res.send({
                msg: '删除成功',
                status: 200
            })
        }
    }
    dbConfig.sqlConnect(sql, [], callback)
}

// 获取用户类型
async function getRole(req, res, next) {
    let sql = 'select roleName as name,roleId as id from role'
    let callback = (err, data) => {
        if (err) {
            res.send({
                msg: '数据库连接有误'
            })
            res.status = 400
        } else {
            res.send({
                data: data
            })
        }
    }
    dbConfig.sqlConnect(sql, [], callback)
}



// 文章
// 获取
async function getArticlelist(req, res, next) {
    let sql = 'select article.id,title,article_con as content,introduce,addTime,type,type.typeName from article,type where article.type  = type.id'
    let callback = (err, data) => {
        if (err) {
            res.send({
                msg: err
            })
        } else {
            res.json({
                data: data
            })
            res.status = 200
        }
    }
    dbconfig.sqlConnect(sql, [], callback)
}

// 添加
async function addArticle(req, res, next) {
    let type = req.body.type
    let title = req.body.title
    let article_con = req.body.article_con.split("'").join("''")
    let introduce = req.body.introduce
    let addTime = new Date().getTime() / 1000
    let sql = `insert into article (type,title,article_con,introduce,addTime) values('${type}','${title}','${article_con}','${introduce}','${addTime}')`
    let call = (err, data) => {
        if (err) {
            res.send({
                msg: err
            })
            res.status = 400
        } else if (data.affectedRows == 1) {
            res.json({
                data: '添加成功',
                status: 200
            })
        }
    }
    dbConfig.sqlConnect(sql, [], call)
}


// 文章类型
async function getArticleType(req, res, next) {
    let sql = 'select * from type'
    let callback = (err, data) => {
        if (err) {
            res.send({
                msg: err
            })
            res.status = 400
        } else {
            res.json({
                data: data
            })
        }
    }
    dbConfig.sqlConnect(sql, [], callback)
}

// 删除文章
async function delArticle(req, res, next) {
    let id = req.query.articleid
    console.log(id)
    let sql = `DELETE FROM article WHERE id = ${id}`
    console.log(sql)
    let callback = (err, data) => {
        if (err) {
            console.log(err)
            res.send(
                {
                    msg: err,
                    status: 401
                }
            )
            res.status = 401
        } else if (data.affectedRows) {
            res.send({
                msg: '删除成功',
                status: 200
            })
        }
    }
    dbConfig.sqlConnect(sql, [], callback)
}

// 根据id获取文章详情
async function getArticleconById(req, res, next) {
    let id = req.query.articleid
    let sql = `select article_con from article where id = ${id}`
    let cb = (err, data) => {
        if (err) {
            res.send({
                status: 401,
                msg: err
            })
            res.status = 401
        } else {
            res.json({
                data: data,
                status: 200
            })
        }
    }
    dbConfig.sqlConnect(sql, [], cb)
}

// 添加种类
async function addType(req, res, next) {
    let type = req.body.type
    let sql = `insert into type (typeName) values ('${type}')`
    let call = (err, data) => {
        if (err) {
            res.send({
                msg: err
            })
            res.status = 400
        } else if (data.affectedRows == 1) {
            res.json({
                data: '添加成功',
                status: 200,
            })
        }
    }
    dbConfig.sqlConnect(sql, [], call)
}
module.exports = {
    login, getUserlist, addUser, delUser, getRole, getArticlelist, addArticle, getArticleType, delArticle, getArticleconById, addType
}